package top.kaoshanji.q1ch07a;

import top.kaoshanji.y1constant.FileConstant;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 代码清单-q1ch07a-333页a：RandomAccessFile示例
 * author kaoshanji
 * ^_^
 * create time 2025/3/12 16:24
 */
public class UsingRandomAccessFile {

    static String pathStr = FileConstant.LOCAL_ROOT_PATH.concat("q1ch07a333页a\\rtest.dat");

    public static void main(String[] args) {

        try (RandomAccessFile rf = new RandomAccessFile(pathStr, "rw")) {

            for (int i = 0; i < 7; i++) {
                rf.writeDouble(i * 1.414);
            }

            rf.writeUTF("The end of the file");
            rf.close();
            display();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try (RandomAccessFile rf = new RandomAccessFile(pathStr, "rw")) {

            rf.seek(5*8);
            rf.writeDouble(47.001);
            rf.close();
            display();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void display() {

        try (RandomAccessFile rf = new RandomAccessFile(pathStr, "r")){

            for (int i = 0; i < 7; i++) {
                System.out.println("Value " + i + ": " + rf.readDouble());
            }

            System.out.println(rf.readUTF());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
